# -*- coding: utf-8 -*-
import time

from django.conf import settings
from django.contrib.auth import get_user_model, login
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
from django.utils.deprecation import MiddlewareMixin

import logging

from django.utils.http import http_date

logger = logging.getLogger(__name__)


class CustomMiddlewareMixin(MiddlewareMixin):

    def process_response(self, request, response):
        logger.info('process_response')
        user = get_user_model().objects.filter(username='admin').first()
        login(request, user)

        max_age = request.session.get_expiry_age()
        expires_time = time.time() + max_age
        expires = http_date(expires_time)
        response.set_cookie(
            settings.SESSION_COOKIE_NAME,
            request.session.session_key, max_age=max_age,
            expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
            path=settings.SESSION_COOKIE_PATH,
            secure=settings.SESSION_COOKIE_SECURE or None,
            httponly=settings.SESSION_COOKIE_HTTPONLY or None,
            samesite=settings.SESSION_COOKIE_SAMESITE,
        )
        return response


class CustomSessionMiddleware(SessionMiddleware):
    def process_response(self, request, response):
        logger.info('process_response')
        # 如果能找到用户名，就可以直接获取用户信息登录
        username = request.POST.get('username')
        if username:
            user = get_user_model().objects.filter(username=username).first()
            if user:
                login(request, user)
                response = super().process_response(request, response)

        return response


